package com.wgj.android.accesslibility.job;

import android.accessibilityservice.AccessibilityService;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jiaai.xui.adapter.XRecyclerViewAdapter;
import com.jiaai.xui.adapter.XViewHolder;
import com.jiaai.xui.adapter.decoration.DividerDecoration;
import com.jiaai.xui.utils.XDensityUtils;
import com.jiaai.xui.utils.log.XLog;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.R;
import com.wgj.android.accesslibility.AccessibilityHelper;
import com.wgj.android.accesslibility.IStatusBarNotification;
import com.wgj.android.accesslibility.config.BatchLocationConfig;
import com.wgj.android.accesslibility.config.WXConfginUtil;
import com.wgj.android.accesslibility.config.WXIDManage;
import com.wgj.android.accesslibility.service.WGJAccessServier;
import com.wgj.android.ui.activity.MainActivity;
import com.wgj.android.utils.Timer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/12/7.
 */

public class AddFriendsByLocationJob implements AccessbilityJob {
    private BatchLocationConfig config;
    private  static  int weixinversion=0;
    private  static  final String TAG="AddFriendsByLocationJob";
    private int i = 0;//记录已打招呼的人数
    private int page = 1;//记录附近的人列表页码,初始页码为1
    private WGJAccessServier service;

    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;
    private boolean viewAdded = false;// 透明窗体是否已经显示
    private View startWarp;
    private View mainWarp;
    private Chronometer time3;
    private View view;// 透明窗体
    private View a1;
    private TextView timepicker;
    private  XRecyclerViewAdapter adapter;
    private  TextView msgText;//进程消息
    private  TextView tvCleanNumber;
    private  TextView tvStatus;//好友状态
    private ImageView animIcon;
    private RecyclerView recyclerView;
    private TextView tvTotalNum;
    private PowerManager.WakeLock wakeLock;

    private String    nickName="";
    private  static   final  int SEND_MSG=1;

    private  boolean isAdd=false;

    private String  className;
    private  int totalNum=0;
    private ArrayList<String> nickNames=new ArrayList<>();
    @Override
    public String getTargetPackageName() {
        return WECHAT_PACKAGENAME;
    }

    @Override
    public void onCreateJob(AccessibilityService service) {
        nickNames=WXConfginUtil.getLocationFriends(service.getApplication());
        /**常亮*/
        PowerManager pm = (PowerManager) service.getApplication().getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "liveTAG");
        wakeLock.acquire();
         this.service= (WGJAccessServier) service;
        config= WXConfginUtil.getBatchLocationConfig(service.getApplication());
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onReceiveJob(final AccessibilityEvent event) {
        className=event.getClassName().toString();
        if(!className.equals("com.tencent.mm.ui.LauncherUI") && !viewAdded){
                AccessibilityHelper.performBack(service);
                return;
        }
        if(className.equals("com.tencent.mm.ui.base.i") && viewAdded){
            AccessibilityNodeInfo nodeInfo=AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),"确定");
            if(nodeInfo!=null){
                AccessibilityHelper.performClick(nodeInfo);
            }
            return;
        }
        if(event.getEventType()==AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED){
            switch (className){
                case "com.tencent.mm.ui.LauncherUI":
                     if(!viewAdded){
                         if(AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),"通讯录")==null){
                             AccessibilityHelper.performBack(service);
                             return;
                         }
                         createWindow();
                     }
                    break;
                case "com.tencent.mm.plugin.nearby.ui.NearbyFriendsUI":
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            selectFriends(event);
                        }
                    },2000);
                    break;
                case "com.tencent.mm.plugin.profile.ui.ContactInfoUI":
                    Log.e(TAG,"ContactInfoUI:"+isAdd);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            opendMsgChar();
                        }
                    },500);

                    break;
                case "com.tencent.mm.ui.contact.SayHiEditUI":
                    //当前在打招呼页面
                    //输入打招呼的内容并发送
                    inputHello(config.getMessgae());
                    AccessibilityHelper.performClick(AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),"发送"));
                    break;
            }
        }

    }

    @Override
    public void onStopJob() {
        WXConfginUtil.closeAddFriendByLocation();
        Intent intent=new Intent(service.getApplication(), MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        service.getApplication().startActivity(intent);

        try {
            time3.stop();
            if(windowManager!=null && view!=null){
                windowManager.removeView(view);
            }
            view=null;
        }catch (Exception e){

        }
        service.stopAddLocationFriendsJob();
        synchronized (this) {
            // sanity check for null as this is a public method
            if (wakeLock != null) {
                XLog.d("Releasing wakelock");
                try {
                    wakeLock.release();
                } catch (Throwable th) {
                    XLog.e("ignoring this exception, probably wakeLock was already released");

                }
            } else {
                // should never happen during normal workflow
                XLog.e("Wakelock reference is null");
            }
        }

    }

    @Override
    public void onNotificationPosted(IStatusBarNotification event) {

    }

    @Override
    public void setWeiXingVersion(int version) {
        weixinversion=version;
    }

    @Override
    public boolean isEnable() {
        return false;
    }

    //自动输入打招呼内容
    private void inputHello(String hello) {
        AccessibilityNodeInfo nodeInfo =service.getRootInActiveWindow();
        //找到当前获取焦点的view
        AccessibilityNodeInfo target =AccessibilityHelper.findNodeInfosById(nodeInfo,WXIDManage.getAddGroupMsgInputId(weixinversion));
        if (target == null) {
            Log.d(TAG, "inputHello: null");
            return;
        }
        Bundle arguments = new Bundle();
        arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, config.getMessgae());
        target.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT,arguments);
    }
    /**
     * 打开消息窗口
     */
    private  void opendMsgChar(){
        if (isAdd) {
            Log.e(TAG,"opendMsgChar back");
            i++;
            isAdd=false;
            AccessibilityHelper.performBack(service);
        } else{
            isAdd=true;
            //从附近的人跳转来的，则点击打招呼按钮
            AccessibilityNodeInfo nodeInfo = service.getRootInActiveWindow();
            if (nodeInfo == null) {
                i++;
                Log.d(TAG, "rootWindow为空");
                AccessibilityHelper.performBack(service);
                return;
            }
            AccessibilityNodeInfo but=AccessibilityHelper.findNodeInfosByText(nodeInfo,"打招呼");
            if (but!=null) {
                AccessibilityHelper.performClick(but);
            } else {
                //如果遇到已加为好友的则界面的“打招呼”变为“发消息"，所以直接返回上一个界面并记录打招呼人数+1
                AccessibilityHelper.performBack(service);
                i++;
            }
        }
    }

    /**
     * 选择附近的好友
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  void selectFriends(AccessibilityEvent event){
        if(config.getMaxSize() !=0 && totalNum==config.getMaxSize() ){
            onStopJob();
            XToast.success("已达到好友数量预设值");
            return;
        }
        List<AccessibilityNodeInfo> list=null;
        //当前在附近的人界面就点选人打招呼
        AccessibilityNodeInfo nodeInfo =service.getRootInActiveWindow();
        if(nodeInfo!=null){
            Log.e(TAG,"获取窗口对像失败");
            list=nodeInfo.findAccessibilityNodeInfosByViewId(WXIDManage.getLocationFriendsAvaterId(weixinversion));
        }else {
            AccessibilityHelper.performHome(service);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ComponentName comp = new ComponentName("com.tencent.mm","com.tencent.mm.ui.LauncherUI");
                    Intent it = new Intent();
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//需要加这个不然会报错
                    it.setComponent(comp);
                    service.getApplication().startActivity(it);
                }
            },300);
            return;
        }

        if (i < (list.size() * page)) {
            list.get(i % list.size()).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            nickName= list.get(i % list.size()).getParent().getChild(0).getText().toString();

                Message message=handler.obtainMessage();
                message.what=SEND_MSG;
                message.obj=nickName;
                handler.sendMessage(message);
                list.get(i % list.size()).getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                nickNames.add(nickName);
                WXConfginUtil.saveLocationFriends(service.getApplication(),nickNames);


        } else if (i == list.size() * page) {
            //本页已全部打招呼，所以下滑列表加载下一页，每次下滑的距离是一屏
            for (int i = 0; i < nodeInfo.getChild(0).getChildCount(); i++) {
                if (nodeInfo.getChild(0).getChild(i).getClassName().equals("android.widget.ListView")) {
                    AccessibilityNodeInfo node_lsv = nodeInfo.getChild(0).getChild(i);
                    if(!node_lsv.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)){
                        onStopJob();
                        XToast.warning("没有更多好友可以打招呼了!",5000).show();
                        return;
                    }
                    page++;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(2000);
                                AccessibilityNodeInfo nodeInfo_ =service.getRootInActiveWindow();
                                List<AccessibilityNodeInfo> list_ = nodeInfo_.findAccessibilityNodeInfosByViewId(WXIDManage.getLocationFriendsAvaterId(weixinversion));
                                //滑动之后，上一页的最后一个item为当前的第一个item，所以从第二个开始打招呼
                                list_.get(1).performAction(AccessibilityNodeInfo.ACTION_CLICK);
                                nickName= list_.get(1).getParent().getChild(0).getText().toString();

                                    Message message=handler.obtainMessage();
                                    message.what=SEND_MSG;
                                    message.obj=nickName;
                                    handler.sendMessage(message);
                                    list_.get(1).getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                                    nickNames.add(nickName);
                                    WXConfginUtil.saveLocationFriends(service.getApplication(),nickNames);


                            } catch (InterruptedException mE) {
                                onStopJob();
                            }

                        }
                    }).start();
                }
            }
        }
    }



    //延迟打开界面
    private void openDelay(final int delaytime, final String text) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(delaytime);
                } catch (InterruptedException mE) {
                    mE.printStackTrace();
                }
                AccessibilityHelper.performClick(AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),text).getParent());
            }
        }).start();
    }

    /**
     * 创建窗口
     */
    private void createWindow(){
        viewAdded=true;
        view = LayoutInflater.from(service).inflate(R.layout.b_add_friends_location_view, null);
        view.findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onStopJob();
            }
        });
        time3=view.findViewById(R.id.time3);
        a1=view.findViewById(R.id.a1);
        tvStatus=view.findViewById(R.id.status);
        msgText=view.findViewById(R.id.msgText);
        animIcon=view.findViewById(R.id.animIcon);
        tvTotalNum=view.findViewById(R.id.totalNum);
        windowManager= (WindowManager) service.getSystemService(service.WINDOW_SERVICE);
        /*
         * LayoutParams.TYPE_SYSTEM_ERROR：保证该悬浮窗所有View的最上层
         * LayoutParams.FLAG_NOT_FOCUSABLE:该浮动窗不会获得焦点，但可以获得拖动
         * PixelFormat.TRANSPARENT：悬浮窗透明
         */
        layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSPARENT);
        layoutParams.flags = layoutParams.flags | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        layoutParams.flags = layoutParams.flags | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; // 排版不受限制
        //悬浮窗开始在右下角显示
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        startWarp=view.findViewById(R.id.startWarp);
        mainWarp=view.findViewById(R.id.mainWarp);
        timepicker=view.findViewById(R.id.timepicker);
        windowManager.addView(view,layoutParams);
        new Timer(timepicker, new Timer.OnCountTimerListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
            @Override
            public void onFinish() {
                startWarp.setVisibility(View.GONE);
                mainWarp.setVisibility(View.VISIBLE);
                a1.startAnimation(createRotateAnimation(360,-360,5000));
                time3.setBase(SystemClock.elapsedRealtime());//计时器清零
                int hour = (int) ((SystemClock.elapsedRealtime() - time3.getBase()) / 1000 / 60);
                time3.setFormat("0"+String.valueOf(hour)+":%s");
                time3.start();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //记录打招呼人数置零
                        i = 0;
                        //当前在微信聊天页就点开发现
                        AccessibilityHelper.performClick(AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),"发现"));
                       if( AccessibilityHelper.findNodeInfosByText(service.getRootInActiveWindow(),"附近的人")==null){
                            onStopJob();
                            XToast.warning("请开启微信附近的人功能",5000).show();
                       }
                        //然后跳转到附近的人
                        openDelay(1000, "附近的人");

                    }
                },200);


            }
        }).start();

    }

    /**
     * uI更新
     */
    Handler handler = new Handler()
    {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what){
                case  SEND_MSG:
                     msgText.setText("正在向:【"+nickName+"】 打招呼");
                     totalNum+=1;
                     tvTotalNum.setText(totalNum+"");
                    break;
            }

        };
    };

    /**
     * 创建旋转动画
     */
    private RotateAnimation createRotateAnimation(int fromDegress, int toDegrees, int duration) {
        RotateAnimation animation = new RotateAnimation(fromDegress, toDegrees, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        //动画执行时间
        animation.setDuration(duration);
        animation.setInterpolator(new LinearInterpolator());
        //动画重复次数-1表示不停重复
        animation.setRepeatCount(-1);
        return  animation;
    }

}
